package com.jack.xiaoer.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Preconditions;
import com.jack.xiaoer.constant.MyConstant;
import com.jack.xiaoer.dto.AccountDTO;
import com.jack.xiaoer.dto.CartDTO;
import com.jack.xiaoer.entity.Cart;
import com.jack.xiaoer.entity.Shop;
import com.jack.xiaoer.service.CartService;
import com.jack.xiaoer.service.error.ProductNotFoundException;
import com.jack.xiaoer.service.error.ServiceException;
import com.jack.xiaoer.service.error.ShopNotFoundException;
import com.jack.xiaoer.util.AjaxResponse;
import com.jack.xiaoer.util.JWTUtil;
import com.jack.xiaoer.validator.Groups;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/19.
 */
@Validated
@RestController
@RequestMapping("/cart")
public class CartController extends BaseController {

    @Autowired
    private CartService cartService;

    @PostMapping("/create")
    public AjaxResponse create(@RequestBody @Validated({Groups.CartCreat.class}) Optional<CartDTO> cartDtoOptional, BindingResult bindingResult) {
        AjaxResponse error = commonValidate(cartDtoOptional, bindingResult);
        if (error != null) {
            return error;
        }

        Cart cart = cartService.add(cartDtoOptional);
        if (cart == null) {
            return AjaxResponse.fail("添加购物车失败");
        }

        return AjaxResponse.success("添加购物车成功", cart);
    }

    @GetMapping("/count/{userId}/{shopId}")
    public AjaxResponse count(@PathVariable Long userId, @PathVariable Long shopId) {
        Integer count = cartService.countItem(userId, shopId, MyConstant.CHECKED);

        return AjaxResponse.success("获取购物车商品数量成功", count);
    }

    @GetMapping("/list/{userId}/{pageNum}/{pageSize}")
    public AjaxResponse list(@PathVariable Long userId, @PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        Preconditions.checkArgument((pageNum > 0 && pageSize > 0)
                , "分页参数异常pageNum=" + pageNum + ", pageSize=" + pageSize);

        IPage<Cart> cartPage = cartService.listByUserId(userId, pageNum, pageSize);

        return AjaxResponse.success("获取购物车列表成功", cartPage);
    }

    @GetMapping("/shopList/{userId}")
    public AjaxResponse shopList(@PathVariable Long userId) {
        List<Shop> shops = cartService.listShopByUserId(userId);

        return AjaxResponse.success("获取购物车中商家成功", shops);
    }

    @GetMapping("/list/{userId}/{shopId}")
    public AjaxResponse listProductByUserIdAndShopId(@PathVariable Long userId, @PathVariable Long shopId) {

        List<Cart> carts = cartService.listByUserIdAndShopId(userId, shopId, false);

        return AjaxResponse.success("获取商品列表成功", carts);
    }

    @GetMapping("/list/checked/{userId}/{shopId}")
    public AjaxResponse listCheckedProductByUserIdAndShopId(@PathVariable Long userId, @PathVariable Long shopId) {
        List<Cart> carts = cartService.listByUserIdAndShopId(userId, shopId, true);

        return AjaxResponse.success("获取商品列表成功", carts);
    }

    @GetMapping("/checked/{cartId}/{checkedCode}")
    public AjaxResponse changeChecked(@PathVariable Long cartId, @PathVariable Integer checkedCode) {

        boolean result = cartService.updateCheckedByCartId(cartId, checkedCode);

        return AjaxResponse.success("修改选中状态成功", result);
    }


    @ExceptionHandler({ServiceException.class})
    public AjaxResponse handleServiceException(ServiceException e) {
        if (e instanceof ShopNotFoundException) {
            return AjaxResponse.invalid("商家不存在");
        }
        if (e instanceof ProductNotFoundException) {
            return AjaxResponse.invalid("商品不存在");
        }

        return AjaxResponse.invalid(e.getMessage());
    }

}
